<template>
  <view v-if="visible" class="map-select-container">
    <!-- 遮罩层 -->
    <view class="mask" @click="handleClose"></view>

    <!-- 地图选择弹窗 -->
    <view class="map-select-modal">
      <!-- 头部 -->
      <view class="modal-header">
        <text class="modal-title">选择位置</text>
        <view class="close-btn" @click="handleClose">
          <text class="close-icon">×</text>
        </view>
      </view>

      <!-- 搜索区域 -->
      <view class="search-section">
        <view class="search-input-wrapper">
          <input
            v-model="searchKeyword"
            class="search-input"
            placeholder="搜索地址"
            @confirm="handleSearch"
          />
          <view class="search-btn" @click="handleSearch">
            <text class="search-icon">🔍</text>
          </view>
        </view>
      </view>

      <!-- 地图容器 -->
      <view class="map-container">
        <Amap
          :center="mapCenter"
          :zoom="mapZoom"
          :markers="mapMarkers"
          container-style="width:100%;height:400rpx;border-radius:8rpx;"
          @marker-click="handleMarkerClick"
        />
      </view>

      <!-- 搜索结果列表 -->
      <view v-if="searchResults.length > 0" class="search-results">
        <view class="results-title">搜索结果</view>
        <scroll-view class="results-list" scroll-y>
          <view
            v-for="(item, index) in searchResults"
            :key="index"
            class="result-item"
            @click="handleSelectLocation(item)"
          >
            <view class="result-name">{{ item.name }}</view>
            <view class="result-address">{{ item.address }}</view>
          </view>
        </scroll-view>
      </view>

      <!-- 底部操作 -->
      <view class="modal-footer">
        <view class="btn-group">
          <view class="btn btn-cancel" @click="handleClose">
            <text class="btn-text">取消</text>
          </view>
          <view class="btn btn-confirm" @click="handleConfirm">
            <text class="btn-text">确认选择</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import Amap from "@/components/map/Amap.vue";
import { MAP_CONFIG, getAmapKey, isAmapKeyConfigured, getAmapErrorMessage } from "@/config/map";

// 定义接口
interface LocationInfo {
  name: string;
  address: string;
  longitude: number;
  latitude: number;
}

interface Props {
  visible: boolean;
  initialLocation?: LocationInfo;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "confirm", location: LocationInfo): void;
}

// 定义 props 和 emits
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  initialLocation: undefined,
});

const emit = defineEmits<Emits>();

// 响应式数据
const searchKeyword = ref("");
const searchResults = ref<LocationInfo[]>([]);
const selectedLocation = ref<LocationInfo | null>(null);

// 地图相关数据
const mapCenter = ref(MAP_CONFIG.DEFAULT_CENTER);
const mapZoom = ref(MAP_CONFIG.DEFAULT_ZOOM);
const mapMarkers = ref([
  {
    position: MAP_CONFIG.DEFAULT_CENTER,
    title: "当前位置",
    icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/2a6a85534eea442cb1a7864c503e9d67.png",
  },
]);

// 监听 visible 变化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.initialLocation) {
      selectedLocation.value = props.initialLocation;
      mapCenter.value = [props.initialLocation.longitude, props.initialLocation.latitude];
      updateMarkers();
    }
  }
);

// 关闭弹窗
const handleClose = () => {
  emit("update:visible", false);
  searchKeyword.value = "";
  searchResults.value = [];
};

// 搜索地址
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim();
  if (!keyword) {
    uni.showToast({
      title: "请输入搜索关键词",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: "搜索中...",
    });

    // 调用真实的地图搜索API
    await searchLocation(keyword, "南昌");

    uni.hideLoading();

    // 如果没有搜索结果，给出提示
    if (searchResults.value.length === 0) {
      uni.showToast({
        title: "未找到相关地点，请尝试其他关键词",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "搜索失败，请检查网络连接",
      icon: "error",
      duration: 2000,
    });
    console.error("搜索失败:", error);
  }
};

// 高德地图搜索API - 仅使用真实API搜索，不包含本地模拟数据
const searchLocation = async (keyword: string, city: string) => {
  console.log("搜索关键词:", keyword, "城市:", city);

  try {
    // 检查是否配置了API密钥
    if (!isAmapKeyConfigured()) {
      console.warn("高德地图API密钥未配置");
      uni.showToast({
        title: "地图API密钥未配置",
        icon: "none",
        duration: 2000
      });
      searchResults.value = [];
      return;
    }

    console.log("使用的API密钥:", getAmapKey());
    
    // 使用高德地图Web服务API进行地点搜索
    const response = await uni.request({
      url: "https://restapi.amap.com/v3/place/text",
      method: "GET",
      data: {
        key: getAmapKey(),
        keywords: keyword,
        city: city || MAP_CONFIG.DEFAULT_CITY, // 使用传入的城市参数或默认城市
        citylimit: "0", // 取消城市限制，增加搜索范围
        output: "json",
        offset: 10, // 增加返回结果数量
        page: 1,
        extensions: "all",
      },
    });

    console.log("API响应状态码:", response.statusCode);
    console.log("API完整响应数据:", response.data);

    if (response.statusCode === 200) {
      const responseData = response.data;

      // 检查API返回状态
      if (responseData.status === "1") {
        if (responseData.pois && responseData.pois.length > 0) {
          const pois = responseData.pois;
          console.log(`API返回${pois.length}个地点`);

          searchResults.value = pois
            .map((poi, index) => {
              try {
                // 记录每个POI数据用于调试
                console.log(`POI ${index + 1}:`, poi);
                
                if (!poi.location || !poi.location.includes(",")) {
                  console.warn(`POI ${index + 1}缺少有效坐标:`, poi.name);
                  return null;
                }
                
                const [longitude, latitude] = poi.location.split(",").map(Number);

                // 验证坐标是否在合理范围内
                if (
                  isNaN(longitude) ||
                  isNaN(latitude) ||
                  longitude < -180 ||
                  longitude > 180 ||
                  latitude < -90 ||
                  latitude > 90
                ) {
                  console.warn(`POI ${index + 1}坐标超出有效范围:`, poi.location);
                  return null;
                }

                return {
                  name: poi.name?.trim() || "未知地点",
                  address: 
                    poi.address?.trim() ||
                    [poi.pname, poi.cityname, poi.adname, poi.business_area]
                      .filter(Boolean)
                      .join(" ") ||
                    `${city || MAP_CONFIG.DEFAULT_CITY}${poi.adname || ""}`,
                  longitude: longitude,
                  latitude: latitude,
                };
              } catch (error) {
                console.error(`处理POI ${index + 1}数据错误:`, error, poi);
                return null;
              }
            })
            .filter(Boolean); // 过滤无效结果

          console.log("最终搜索结果数量:", searchResults.value.length);
          if (searchResults.value.length === 0) {
            console.warn("所有POI数据过滤后为空");
            uni.showToast({
              title: "未找到有效地点数据",
              icon: "none",
              duration: 2000
            });
          }
        } else {
          console.warn("API返回无POI数据", { pois: responseData.pois });
          // 显示具体API返回信息
          if (responseData.info) {
            console.warn("API返回信息:", responseData.info);
            uni.showToast({
              title: responseData.info,
              icon: "none",
              duration: 2000
            });
          }
          searchResults.value = [];
        }
      } else {
        // API返回错误状态
        console.error("API返回错误状态:", responseData.status, responseData.info);
        
        let errorMessage = responseData.info || "未知错误";
        
        // 特别处理USERKEY_PLAT_NOMATCH错误
        if (responseData.info && responseData.info.includes("USERKEY_PLAT_NOMATCH")) {
          errorMessage = getAmapErrorMessage("USERKEY_PLAT_NOMATCH");
          
          // 尝试使用备用API密钥
          console.log("尝试使用备用搜索");
          try {
            // 使用备用密钥重新发起请求
            const fallbackResponse = await uni.request({
              url: "https://restapi.amap.com/v3/place/text",
              method: "GET",
              data: {
                key: getFallbackAmapKey(),
                keywords: keyword,
                city: city || MAP_CONFIG.DEFAULT_CITY,
                citylimit: "0",
                output: "json",
                offset: 10,
                page: 1,
                extensions: "all",
              },
            });
            
            console.log("备用密钥API响应:", fallbackResponse);
            
            if (fallbackResponse.statusCode === 200) {
              const fallbackData = fallbackResponse.data;
              if (fallbackData.status === "1" && fallbackData.pois && fallbackData.pois.length > 0) {
                // 处理备用密钥返回的结果
                searchResults.value = fallbackData.pois
                  .map((poi, index) => {
                    try {
                      if (!poi.location || !poi.location.includes(",")) {
                        console.warn(`备用POI ${index + 1}缺少有效坐标:`, poi.name);
                        return null;
                      }
                      
                      const [longitude, latitude] = poi.location.split(",").map(Number);
                      
                      if (
                        isNaN(longitude) ||
                        isNaN(latitude) ||
                        longitude < -180 ||
                        longitude > 180 ||
                        latitude < -90 ||
                        latitude > 90
                      ) {
                        console.warn(`备用POI ${index + 1}坐标超出有效范围:`, poi.location);
                        return null;
                      }
                      
                      return {
                        name: poi.name?.trim() || "未知地点",
                        address: 
                          poi.address?.trim() ||
                          [poi.pname, poi.cityname, poi.adname, poi.business_area]
                            .filter(Boolean)
                            .join(" ") ||
                          `${city || MAP_CONFIG.DEFAULT_CITY}${poi.adname || ""}`,
                        longitude: longitude,
                        latitude: latitude,
                      };
                    } catch (error) {
                      console.error(`处理备用POI ${index + 1}数据错误:`, error, poi);
                      return null;
                    }
                  })
                  .filter(Boolean);
                
                console.log("备用密钥搜索结果数量:", searchResults.value.length);
                
                // 如果备用密钥也没有返回有效结果，才显示错误
                if (searchResults.value.length === 0) {
                  uni.showToast({
                    title: "备用密钥也未找到有效数据",
                    icon: "none",
                    duration: 3000
                  });
                }
                
                // 即使找到结果，也通知用户密钥配置有问题
                uni.showToast({
                  title: "地图服务配置问题，正在尝试备用方案",
                  icon: "none",
                  duration: 3000
                });
                
                return; // 成功获取备用结果后，不再执行后续错误处理
              }
            }
          } catch (fallbackError) {
            console.error("备用密钥请求失败:", fallbackError);
          }
        }
        
        uni.showToast({
          title: errorMessage,
          icon: "none",
          duration: 3000
        });
        searchResults.value = [];
      }
    } else {
      console.error("API请求失败:", response.statusCode, response);
      uni.showToast({
        title: `请求失败: ${response.statusCode}`,
        icon: "error",
        duration: 2000
      });
      searchResults.value = [];
    }
  } catch (error) {
    console.error("地图搜索错误:", error);
    uni.showToast({
      title: "网络错误，请检查连接",
      icon: "error",
      duration: 2000
    });
    searchResults.value = [];
  }
};

// 由于要求移除所有本地模拟数据，备用搜索方法已被移除
// 搜索功能现在完全依赖高德地图API

// 选择搜索结果
const handleSelectLocation = (location: LocationInfo) => {
  selectedLocation.value = location;
  mapCenter.value = [location.longitude, location.latitude];
  updateMarkers();
  searchResults.value = [];
  searchKeyword.value = location.name;

  // 立即更新地图显示
  console.log("选择位置:", location);
};

// 点击地图标记
const handleMarkerClick = (marker: any) => {
  console.log("点击标记:", marker);
};

// 更新地图标记
const updateMarkers = () => {
  if (selectedLocation.value) {
    mapMarkers.value = [
      {
        position: [selectedLocation.value.longitude, selectedLocation.value.latitude],
        title: selectedLocation.value.name,
        icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/2a6a85534eea442cb1a7864c503e9d67.png",
      },
    ];
    console.log("更新地图标记:", mapMarkers.value);
  }
};

// 确认选择
const handleConfirm = () => {
  if (!selectedLocation.value) {
    uni.showToast({
      title: "请先选择位置",
      icon: "none",
    });
    return;
  }

  console.log("确认选择位置:", selectedLocation.value);
  emit("confirm", selectedLocation.value);
  handleClose();
};
</script>

<style lang="scss" scoped>
.map-select-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.map-select-modal {
  position: relative;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f0f0f0;
  transition: all 0.3s ease;
}

.close-btn:active {
  background-color: #e0e0e0;
}

.close-icon {
  font-size: 32rpx;
  color: #666;
  font-weight: bold;
}

.search-section {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  overflow: hidden;
}

.search-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
}

.search-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1989fa;
  transition: all 0.3s ease;
}

.search-btn:active {
  background-color: #1677dd;
}

.search-icon {
  font-size: 28rpx;
  color: #fff;
}

.map-container {
  padding: 20rpx 30rpx;
  flex: 1;
  min-height: 400rpx;
}

.search-results {
  max-height: 300rpx;
  border-top: 1rpx solid #f0f0f0;
}

.results-title {
  padding: 20rpx 30rpx 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.results-list {
  max-height: 250rpx;
}

.result-item {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  transition: all 0.3s ease;
}

.result-item:active {
  background-color: #f8f9fa;
}

.result-item:last-child {
  border-bottom: none;
}

.result-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  font-weight: 500;
}

.result-address {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
}

.modal-footer {
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.btn-group {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.btn-cancel {
  background-color: #f0f0f0;
}

.btn-cancel:active {
  background-color: #e0e0e0;
}

.btn-confirm {
  background-color: #1989fa;
}

.btn-confirm:active {
  background-color: #1677dd;
}

.btn-text {
  font-size: 28rpx;
  font-weight: 500;
}

.btn-cancel .btn-text {
  color: #666;
}

.btn-confirm .btn-text {
  color: #fff;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .map-select-modal {
    width: 95%;
    max-height: 85vh;
  }

  .modal-header {
    padding: 20rpx;
  }

  .search-section {
    padding: 15rpx 20rpx;
  }

  .map-container {
    padding: 15rpx 20rpx;
  }

  .results-title {
    padding: 15rpx 20rpx 10rpx;
  }

  .result-item {
    padding: 15rpx 20rpx;
  }

  .modal-footer {
    padding: 15rpx 20rpx;
  }
}
</style>
